package net.bwie.jtp.dws.log.job;
import net.bwie.jtp.dws.log.Function.PageViewBeanMapFunction;
import com.alibaba.fastjson.JSON;
import net.bwie.jtp.dws.log.Function.PageViewReportReduceFunction;
import net.bwie.jtp.dws.log.Function.PageViewReportWindowFunction;
import net.bwie.jtp.dws.log.Function.PageViewWindowFunction;
import net.bwie.jtp.dws.log.bean.PageViewBean;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class JtpTrafficPageViewMinuteWindowDwsJob {
    public static void main(String[] args) throws Exception {
        // 1-创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //  2-数据源source
        DataStream<String> pageDataStream = KafkaUtil.consumerKafka(env, "dwd-traffic-page-log");
        pageDataStream.print("page");


        // 3-数据转换transformation
        DataStream<String> resultStream = handle(pageDataStream);
        // 4-数据输出sink
        JdbcUtil.sinkToClickhouseUpsert(
                resultStream,
                "INSERT INTO jtp_log_report.dws_log_page_view_window_report(\n" +
                        "    window_start_time, window_end_time,\n" +
                        "    brand, channel, province, is_new,\n" +
                        "    pv_count, pv_during_time, uv_count, session_count,\n" +
                        "    ts\n" +
                        ")\n" +
                        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );

        // 5-触发执行
        env.execute("JtpTrafficPageViewMinuteWindowDwsJob");





    }

    private static DataStream<String> handle(DataStream<String> pageDataStream) {

        //  1-按照mid(设备id)分组,计算uv 通过状态编程state记录今天是否第一次访问
        KeyedStream<String, String> midStream = pageDataStream.keyBy(
                json -> JSON.parseObject(json).getJSONObject("common").getString("mid")
        );

        // 2- 将每条数据封装为实体类bean对象
        DataStream<PageViewBean> beanStream = midStream.map(new PageViewBeanMapFunction());
        //3-事件时间字段和水位线
        SingleOutputStreamOperator<PageViewBean> timeStream = beanStream.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<PageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<PageViewBean>() {
                                    @Override
                                    public long extractTimestamp(PageViewBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                }
                        )
        );

        //4-分组keyBy：ar地区、ba品牌、ch渠道、is_new新老访客
        KeyedStream<PageViewBean, String> keyedStream = timeStream.keyBy(
                bean -> bean.getBrand()+ "," + bean.getChannel()+ "," + bean.getProvince() + "," + bean.getIsNew()
        );

        //5-滚动窗口:大小为1分钟

        WindowedStream<PageViewBean, String, TimeWindow> windowStream = keyedStream.window(
                TumblingEventTimeWindows.of(Time.minutes(1))
        );

        //6 聚合 对窗口中的数据进行聚合计算
        DataStream<String> reportStream = windowStream.apply(new PageViewWindowFunction());

//        //todo 使用reduce 算子，对窗口数据进行增量计算
//        DataStream<String> reportStream = windowStream.reduce(
//                new PageViewReportReduceFunction(), new PageViewReportWindowFunction()
//        );

        //返回结果
        return reportStream;
    }
}
